package com.whfc.common.weixin.mp;

import com.alibaba.fastjson.JSONObject;
import com.whfc.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 小程序登陆接口
 */
public class LoginApi {

    private static Logger logger = LoggerFactory.getLogger(LoginApi.class);

    public static String URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    public static final String SESSION_KEY = "session_key";

    public static final String OPENID = "openid";

    /**
     * code 换取 session_key
     *
     * @param appid
     * @param secret
     * @param js_code
     * @return
     */
    public static SessionKey code2session(String appid, String secret, String js_code) {

        String url = String.format(URL, appid, secret, js_code);

        String response = HttpUtil.doGet(url);

        logger.info("调用code2session接口,url:{},response:{}", url, response);

        JSONObject retJSON = JSONObject.parseObject(response);

        SessionKey sessionKey = null;
        if (retJSON != null && retJSON.containsKey(SESSION_KEY) && retJSON.containsKey(OPENID)) {
            sessionKey = JSONObject.parseObject(response, SessionKey.class);
        }

        return sessionKey;
    }
}
